<template>
  <div class="demo-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>采购管理</el-breadcrumb-item>
      <el-breadcrumb-item>采购</el-breadcrumb-item>
    </el-breadcrumb>
    <br>

    <!-- 条件查询区域 -->
    <el-card class="card search-card" shadow="hover">
      <el-form :model="searchForm" :inline="true" label-width="80px">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.OrderNo" placeholder="请输入订单号" clearable style="width: 200px" />
        </el-form-item>

        <el-form-item label="供应商">
          <el-select v-model="searchForm.SupplierId" placeholder="请选择供应商" clearable style="width: 200px">
            <el-option label="远航复合材料有限公司" value="1" />
            <el-option label="浪尖户外材料贸易" value="2" />
            <el-option label="蓝海船用物资批发" value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="日期范围">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 300px" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作和内容区域 -->
    <el-card class="card content-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="operation-buttons">
            <el-button type="primary" @click="handlePurchase"><el-icon>
                <Plus />
              </el-icon>采购商品</el-button>

          </div>
        </div>
      </template>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange" border stripe
        style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单号" min-width="150" />
        <el-table-column prop="purchaseDate" label="采购日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.purchaseDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="supplierId" label="供应商" width="150">
          <template #default="{ row }">
            {{ getSupplierName(row.supplierId) }}
          </template>
        </el-table-column>
        <el-table-column prop="purchaser" label="采购员" width="100" />
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template #default="{ row }">
            <span style="color: #e6a23c; font-weight: bold;">¥{{ row.totalAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetails(row)">
              <el-icon>
                <View />
              </el-icon>查看详情
            </el-button>

            <!-- 添加入库按钮 -->
            <el-button type="success" size="small" @click="handleInbound(row)" v-if="row.status === '未入库'">
              <el-icon>
                <Box />
              </el-icon>入库
            </el-button>

          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页区域 -->
    <el-card class="card pagination-card" shadow="hover">
      <div class="pagination-container">
        <div class="pagination-info">
          <span>共 {{ total }} 条记录，当前显示第 {{ (currentPage - 1) * pageSize + 1 }} - {{ Math.min(currentPage * pageSize,
            total)
          }} 条</span>
        </div>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>
  </div>

  <!-- 订单详情弹窗 -->
  <el-dialog v-model="detailsDialogVisible" title="采购订单详情" width="900px" :before-close="handleCloseDetails">
    <div v-if="selectedOrder" class="order-details">
      <!-- 订单基本信息 -->
      <el-descriptions :column="3" border title="订单基本信息">
        <el-descriptions-item label="订单号">{{ selectedOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="采购日期">{{ formatDate(selectedOrder.purchaseDate) }}</el-descriptions-item>
        <el-descriptions-item label="供应商">{{ getSupplierName(selectedOrder.supplierId) }}</el-descriptions-item>
        <el-descriptions-item label="采购员">{{ selectedOrder.purchaser }}</el-descriptions-item>
        <el-descriptions-item label="总金额">
          <span style="color: #e6a23c; font-weight: bold; font-size: 16px;">¥{{ selectedOrder.totalAmount }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(selectedOrder.status)">{{ selectedOrder.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="3">{{ selectedOrder.remark || '无' }}</el-descriptions-item>
      </el-descriptions>

      <!-- 商品信息 -->
      <div style="margin-top: 20px;">
        <h4>商品清单</h4>
        <el-table :data="parsedProducts" border stripe style="width: 100%">
          <el-table-column prop="productName" label="商品名称" min-width="150" />
          <el-table-column prop="specification" label="规格型号" min-width="150" />
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="{ row }">
              <span>¥{{ row.unitPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="subtotal" label="小计" width="120">
            <template #default="{ row }">
              <span style="color: #67c23a; font-weight: bold;">¥{{ row.subtotal }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="detailsDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 采购商品弹窗 -->
  <el-dialog v-model="purchaseDialogVisible" title="采购商品" width="1000px" :before-close="handleClosePurchase">
    <div class="purchase-form">
      <!-- 供应商选择 -->
      <el-form :model="purchaseForm" label-width="100px" style="margin-bottom: 20px;">
        <el-form-item label="选择供应商">
          <el-select v-model="purchaseForm.supplierId" placeholder="请选择供应商" style="width: 300px"
            @change="handleSupplierChange" clearable>
            <el-option v-for="supplier in supplierList" :key="supplier.id" :label="supplier.name"
              :value="supplier.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="purchaseForm.remark" placeholder="请输入备注信息" style="width: 300px" type="textarea"
            :rows="2" />
        </el-form-item>
      </el-form>

      <!-- 商品选择表格 -->
      <div v-if="purchaseForm.supplierId">
        <h4>可采购商品</h4>
        <el-table :data="availableProducts" border stripe style="width: 100%"
          @selection-change="handleProductSelectionChange" :row-class-name="getRowClassName">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="productName" label="商品名称" min-width="150" />
          <el-table-column prop="specification" label="规格型号" min-width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="supplyPrice" label="供应价格" width="120">
            <template #default="{ row }">
              <span>¥{{ row.supplyPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="isDefault" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status == 1 ? 'success' : 'danger'">
                {{ row.status == 1 ? '上架' : '下架' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="采购数量" width="150">
            <template #default="{ row }">
              <el-input-number v-model="row.quantity" :min="1" :max="9999" size="small" style="width: 100px"
                @change="calculateTotal" />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 采购汇总 -->
      <div v-if="selectedProducts.length > 0" style="margin-top: 20px;">
        <h4>采购汇总</h4>
        <el-table :data="selectedProducts" border stripe style="width: 100%">
          <el-table-column prop="productName" label="商品名称" min-width="150" />
          <el-table-column prop="specification" label="规格型号" min-width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="supplyPrice" label="单价" width="100">
            <template #default="{ row }">
              <span>¥{{ row.supplyPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              <span style="color: #67c23a; font-weight: bold;">¥{{ (row.supplyPrice * row.quantity).toFixed(2) }}</span>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 15px; text-align: right;">
          <span style="font-size: 18px; font-weight: bold; color: #e6a23c;">
            总金额：¥{{ totalAmount.toFixed(2) }}
          </span>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="purchaseDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitPurchase" :disabled="selectedProducts.length === 0">
          提交采购
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 入库操作弹窗 - 与采购商品弹窗风格一致 -->
  <el-dialog v-model="inboundDialogVisible" title="商品入库" width="1000px" :before-close="handleCloseInbound">
    <div class="inbound-form">
      <!-- 仓库选择 -->
      <el-form :model="inboundForm" label-width="100px" style="margin-bottom: 20px;">
        <el-form-item label="选择仓库">
          <el-select v-model="inboundForm.warehouseId" placeholder="请选择仓库" style="width: 300px"
            @change="handleWarehouseChange" clearable>
            <el-option v-for="warehouse in warehouseList" :key="warehouse.id" :label="warehouse.warehouseName"
              :value="warehouse.id" />
          </el-select>
        </el-form-item>
        <!-- 入库备注 -->
        <el-form :model="inboundForm" label-width="100px" style="margin-top: 20px;">
          <el-form-item label="入库备注">
            <el-input v-model="inboundForm.remark" type="textarea" :rows="3" placeholder="请输入入库备注信息" />
          </el-form-item>
        </el-form>
      </el-form>

      <!-- 库位选择 -->
      <div v-if="inboundForm.warehouseId">
        <h4>库位选择</h4>
        <el-table :data="locationList" border stripe style="width: 100%"
          @selection-change="handleLocationSelectionChange" :row-class-name="getLocationRowClassName">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="locationName" label="库区名称" min-width="150" />
          <el-table-column prop="capacity" label="容量" width="120">
            <template #default="{ row }">
              {{ row.capacity }}m³
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
        </el-table>
      </div>

      <!-- 货位选择 -->
      <div v-if="selectedLocations.length > 0" style="margin-top: 20px;">
        <h4>货位选择</h4>
        <el-table :data="binList" border stripe style="width: 100%" @selection-change="handleBinSelectionChange"
          :row-class-name="getBinRowClassName">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="binName" label="货位名称" min-width="150" />
          <el-table-column prop="binType" label="货位类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getBinTypeTagType(row.binType)">
                {{ getBinTypeLabel(row.binType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="maxWeight" label="最大重量" width="120">
            <template #default="{ row }">
              {{ row.maxWeight }}kg
            </template>
          </el-table-column>
          <el-table-column prop="usedWeight" label="已用重量" width="120">
            <template #default="{ row }">
              {{ row.usedWeight }}kg
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
        </el-table>
      </div>

      <!-- 可入库商品 -->
      <div style="margin-top: 20px;">
        <h4>可入库商品</h4>
        <el-table :data="inboundProducts" border stripe style="width: 100%"
          @selection-change="handleInboundProductSelectionChange" :row-class-name="getInboundRowClassName">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="productName" label="商品名称" min-width="200" />
          <el-table-column prop="specification" label="规格" width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="quantity" label="采购数量" width="120" />
          <el-table-column prop="unitPrice" label="单价" width="120">
            <template #default="{ row }">
              ¥{{ row.unitPrice }}
            </template>
          </el-table-column>
          <el-table-column label="入库数量" width="150">
            <template #default="{ row }">
              <el-input-number v-model="row.inboundQuantity" :min="1" :max="row.quantity" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              <span style="color: #e6a23c; font-weight: bold;">
                ¥{{ (row.unitPrice * row.inboundQuantity).toFixed(2) }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCloseInbound">取消</el-button>
        <el-button type="primary" @click="handleSubmitInbound">
          确认入库
        </el-button>
      </div>
    </template>
  </el-dialog>


</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Download, View } from '@element-plus/icons-vue'
import http from '@/Axios/Htttp';

// 搜索表单数据
const searchForm = reactive({ OrderNo: '', SupplierId: '', dateRange: [] })

// 定义表格数据类型
interface TableItem {
  id: number;
  orderNo: string;
  purchaseDate: string;
  supplierId: number;
  purchaser: string;
  productsInfo: string;
  totalAmount: number;
  status: string;
  remark: string;
}




// ==================== 入库相关数据类型定义 ====================

/**
 * 库位数据类型定义 - 参考WarehouseArea.vue的实际字段
 */
interface LocationItem {
  id: number;                    // 库位ID
  locationCode: string;          // 库位编号
  locationName: string;          // 库位名称
  capacity: number;              // 库位容量
  warehouseName: string;         // 所属仓库名称
  managerName: string;           // 库位管理员
  status: number;                // 状态：1-启用，2-停用，3-锁定
  remark: string;                // 备注
  createBy: string;              // 创建者
  [key: string]: any;            // 索引签名
}

/**
 * 货位数据类型定义 - 参考GoodsAllocation.vue的实际字段
 */
interface BinItem {
  id: number;                    // 货位ID
  binCode: string;               // 货位编号
  binName: string;               // 货位名称
  binType: string;               // 货位类型
  length: number;                // 长度
  width: number;                 // 宽度
  height: number;                // 高度
  usedWeight: number;            // 已用重量
  maxWeight: number;             // 最大重量
  usedVolume: number;            // 已用体积
  locationName: string;          // 所属库位名称
  warehouseName: string;         // 所属仓库名称
  status: number;                // 状态：1-启用，2-停用，3-锁定
  sortOrder: number;             // 排序号
  remark: string;                // 备注
  createBy: string;              // 创建者
  createTime: string;            // 创建时间
  [key: string]: any;            // 索引签名
}




// 表格数据 - 添加正确的类型声明
const tableData = ref<TableItem[]>([]);
const loading = ref(false);
const selectedRows = ref<TableItem[]>([]);
const hasSelection = ref(false);

// 分页数据
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 订单详情弹窗相关
const detailsDialogVisible = ref(false);
const selectedOrder = ref<TableItem | null>(null);
const parsedProducts = ref<any[]>([]);

// 采购商品弹窗相关
const purchaseDialogVisible = ref(false);
const purchaseForm = reactive({
  supplierId: '',
  remark: ''
});
const supplierList = ref<any[]>([]);
const availableProducts = ref<any[]>([]);
const selectedProducts = ref<any[]>([]);
const totalAmount = ref(0);

// 工具函数
const formatDate = (dateString: string): string => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const getSupplierName = (supplierId: number): string => {
  const supplierMap: { [key: number]: string } = {
    1: '远航复合材料有限公司',
    2: '浪尖户外材料贸易',
    3: '蓝海船用物资批发'
  }
  return supplierMap[supplierId] || `供应商${supplierId}`
}

const getStatusTagType = (status: string): string => {
  const statusMap: { [key: string]: string } = {
    '草稿': 'info',
    '已完成': 'success',
    '进行中': 'warning',
    '已取消': 'danger',
    '未入库': 'warning' // 添加未入库状态
  }
  return statusMap[status] || 'info'
}

// 生成订单号
const generateOrderNo = (): string => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hour = String(now.getHours()).padStart(2, '0');
  const minute = String(now.getMinutes()).padStart(2, '0');
  const second = String(now.getSeconds()).padStart(2, '0');
  return `D${year}${month}${day}${hour}${minute}${second}`;
}

// 数据加载
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      PageIndex: currentPage.value,
      PageSize: pageSize.value,
      OrderNo: searchForm.OrderNo,
      SupplierId: searchForm.SupplierId,
      StartDate: searchForm.dateRange?.[0] || '',
      EndDate: searchForm.dateRange?.[1] || ''
    }

    const response = await http.get("api/SuppersProduct/GetPurchaseOrderPage", {
      params,
      cache: false
    })

    if (response.data.code === 200) {
      tableData.value = response.data.pageData
      total.value = response.data.todalCount
    } else {
      ElMessage.error(response.data.message || '数据加载失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('数据加载失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 获取供应商列表
const getSupplierList = async () => {
  try {
    const response = await http.get("api/SuppersProduct/GetSupplierDropdown");
    if (response.data.code === 200) {
      supplierList.value = response.data.result;
    } else {
      ElMessage.error(response.data.message || '获取供应商列表失败');
    }
  } catch (error) {
    console.error('获取供应商列表失败:', error);
    ElMessage.error('获取供应商列表失败，请检查网络连接');
  }
}

// 获取可采购商品列表
const getAvailableProducts = async () => {
  if (!purchaseForm.supplierId) {
    availableProducts.value = [];
    selectedProducts.value = [];
    totalAmount.value = 0;
    return;
  }
  try {
    const response = await http.get("api/SuppersProduct/GetPurchaseProductsBySupplier", {
      params: { supplierId: purchaseForm.supplierId },
      cache: false
    });
    if (response.data.code === 200) {
      // 过滤掉下架商品，只显示上架商品
      const filteredProducts = response.data.result
        .filter((item: any) => item.status == 1) // 只保留上架商品
        .map((item: any) => ({
          ...item,
          quantity: 1 // 默认数量为1
        }));

      availableProducts.value = filteredProducts;
      selectedProducts.value = []; // 清空已选商品
      totalAmount.value = 0;
    } else {
      ElMessage.error(response.data.message || '获取可采购商品失败');
    }
  } catch (error) {
    console.error('获取可采购商品失败:', error);
    ElMessage.error('获取可采购商品失败，请检查网络连接');
  }
}

// 供应商选择变化时触发
const handleSupplierChange = () => {
  getAvailableProducts();
}

// 商品选择变化时触发
const handleProductSelectionChange = (selection: any) => {
  selectedProducts.value = selection;
  calculateTotal();
}

// 计算总金额
const calculateTotal = () => {
  totalAmount.value = selectedProducts.value.reduce((sum, item) => sum + (item.supplyPrice * item.quantity), 0);
}

// 提交采购
const handleSubmitPurchase = async () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要采购的商品');
    return;
  }

  try {
    // 构造商品信息并序列化
    const productsInfoArr = selectedProducts.value.map(item => ({
      productId: item.productId,
      productName: item.productName,
      specification: item.specification,
      unit: item.unit,
      quantity: item.quantity,
      unitPrice: item.supplyPrice,
      subtotal: item.supplyPrice * item.quantity
    }));

    const purchaseData = {
      id: 0,
      orderNo: generateOrderNo(), // 自动生成订单号
      purchaseDate: new Date().toISOString(),
      supplierId: purchaseForm.supplierId,
      purchaser: 'admin', // 固定为admin
      productsInfo: JSON.stringify(productsInfoArr),
      totalAmount: totalAmount.value,
      status: '未入库', // 修改为未入库状态
      remark: purchaseForm.remark || ''
    };

    const response = await http.post("api/SuppersProduct/CreatePurchaseOrder", purchaseData);
    if (response.data.code === 200) {
      ElMessage.success('采购订单创建成功！');
      purchaseDialogVisible.value = false;
      loadData(); // 刷新列表
    } else {
      ElMessage.error(response.data.message || '采购订单创建失败');
    }
  } catch (error) {
    console.error('创建采购订单失败:', error);
    ElMessage.error('创建采购订单失败，请检查网络连接');
  }
}

// 关闭采购弹窗
const handleClosePurchase = () => {
  purchaseDialogVisible.value = false;
  purchaseForm.supplierId = '';
  purchaseForm.remark = '';
  availableProducts.value = [];
  selectedProducts.value = [];
  totalAmount.value = 0;
}

// 查看详情
const handleViewDetails = (row: any) => {
  selectedOrder.value = row;
  try {
    parsedProducts.value = JSON.parse(row.productsInfo);
  } catch (error) {
    console.error('解析商品信息失败:', error);
    ElMessage.error('商品信息解析失败');
    parsedProducts.value = [];
  }
  detailsDialogVisible.value = true;
}

// 关闭详情弹窗
const handleCloseDetails = () => {
  detailsDialogVisible.value = false;
  selectedOrder.value = null;
  parsedProducts.value = [];
}



// ==================== 入库相关响应式数据定义 ====================

/**
 * 入库相关数据
 */
const inboundDialogVisible = ref(false);
const selectedInboundOrder = ref<TableItem | null>(null);
const inboundForm = reactive({
  warehouseId: '',
  remark: ''
});

/**
 * 仓库、库位、货位列表数据
 */
const warehouseList = ref<any[]>([]);
const locationList = ref<LocationItem[]>([]);
const binList = ref<BinItem[]>([]);

/**
 * 选中的库位、货位、商品数据
 */
const selectedLocations = ref<LocationItem[]>([]);
const selectedBins = ref<BinItem[]>([]);
const inboundProducts = ref<any[]>([]);
const selectedInboundProducts = ref<any[]>([]);
const totalInboundAmount = ref(0);
// ==================== 入库相关方法 ====================

/**
 * 打开入库对话框
 * 初始化入库表单和商品数据
 * @param row 选中的采购订单行数据
 */
const handleInbound = (row: TableItem) => {
  selectedInboundOrder.value = row;
  try {
    // 解析采购订单中的商品信息
    const products = JSON.parse(row.productsInfo);
    inboundProducts.value = products.map((item: any) => ({
      ...item,
      inboundQuantity: 1, // 默认入库数量为1
      status: 1 // 默认上架状态
    }));

    // 重置选择状态
    selectedLocations.value = [];
    selectedBins.value = [];
    selectedInboundProducts.value = [];
    totalInboundAmount.value = 0;
  } catch (error) {
    console.error('解析商品信息失败:', error);
    ElMessage.error('商品信息解析失败');
    inboundProducts.value = [];
  }

  inboundDialogVisible.value = true;
  getWarehouseList(); // 获取仓库列表
}

/**
 * 关闭入库对话框
 * 清空所有相关数据
 */
const handleCloseInbound = () => {
  inboundDialogVisible.value = false;
  selectedInboundOrder.value = null;

  // 重置表单数据
  inboundForm.warehouseId = '';
  inboundForm.remark = '';

  // 清空列表数据
  locationList.value = [];
  binList.value = [];
  selectedLocations.value = [];
  selectedBins.value = [];
  inboundProducts.value = [];
  selectedInboundProducts.value = [];
  totalInboundAmount.value = 0;
}

/**
 * 获取仓库列表
 * 参考WarehouseShow.vue的接口调用方式
 */
const getWarehouseList = async () => {
  try {
    const response = await http.get('/api/WMS_Warehouse/GetWarehousePageList', {
      params: {
        PageIndex: 1,
        PageSize: 1000,
        Keyword: '',
        Status: 1, // 只获取启用的仓库
        DepartmentId: '',
        ManagerId: ''
      }
    });

    if (response.data.code === 200) {
      warehouseList.value = response.data.pageData || [];
      console.log('仓库列表加载成功:', warehouseList.value);
    } else {
      console.error('获取仓库列表失败:', response.data.message);
      ElMessage.error(response.data.message || '获取仓库列表失败');
    }
  } catch (error) {
    console.error('获取仓库列表异常:', error);
    ElMessage.error('获取仓库列表失败');
  }
}

/**
 * 仓库选择变化处理
 * 当选择仓库时，获取对应的库位列表
 */
const handleWarehouseChange = () => {
  // 清空之前的选择
  selectedLocations.value = [];
  selectedBins.value = [];
  selectedInboundProducts.value = [];
  totalInboundAmount.value = 0;

  if (inboundForm.warehouseId) {
    getLocationList(); // 获取库位列表
  } else {
    locationList.value = [];
    binList.value = [];
  }
}

/**
 * 获取库位列表
 * 参考WarehouseArea.vue的接口调用方式
 */
const getLocationList = async () => {
  try {
    const response = await http.get('/api/WMS_Location/GetLocationPageList', {
      params: {
        PageIndex: 1,
        PageSize: 1000,
        Keyword: '',
        Status: 1, // 只获取启用的库位
        WarehouseId: inboundForm.warehouseId
      }
    });

    if (response.data.code === 200) {
      // 过滤掉停用的库位
      locationList.value = (response.data.pageData || []).filter((location: any) => location.status === 1);
      console.log('库位列表加载成功:', locationList.value);
    } else {
      console.error('获取库位列表失败:', response.data.message);
      ElMessage.error(response.data.message || '获取库位列表失败');
    }
  } catch (error) {
    console.error('获取库位列表异常:', error);
    ElMessage.error('获取库位列表失败');
  }
}

/**
 * 库位选择变化处理
 * 当选择库位时，获取对应的货位列表
 * @param selection 选中的库位列表
 */
const handleLocationSelectionChange = (selection: LocationItem[]) => {
  selectedLocations.value = selection;

  // 清空货位和商品选择
  selectedBins.value = [];
  selectedInboundProducts.value = [];
  totalInboundAmount.value = 0;

  if (selection.length > 0) {
    getBinList(); // 获取货位列表
  } else {
    binList.value = [];
  }
}

/**
 * 获取货位列表
 * 参考GoodsAllocation.vue的接口调用方式
 */
const getBinList = async () => {
  try {
    const response = await http.get('/api/WMS_Bin/GetBinPageList', {
      params: {
        PageIndex: 1,
        PageSize: 1000,
        Keyword: '',
        Status: 1, // 只获取启用的货位
        WarehouseId: inboundForm.warehouseId
      }
    });

    if (response.data.code === 200) {
      // 过滤出属于选中库位的货位，并过滤掉停用的货位
      const allBins = response.data.pageData || [];
      binList.value = allBins.filter((bin: any) =>
        selectedLocations.value.some((location: any) => location.id === bin.locationId) &&
        bin.status === 1
      );
      console.log('货位列表加载成功:', binList.value);
    } else {
      console.error('获取货位列表失败:', response.data.message);
      ElMessage.error(response.data.message || '获取货位列表失败');
    }
  } catch (error) {
    console.error('获取货位列表异常:', error);
    ElMessage.error('获取货位列表失败');
  }
}

/**
 * 货位选择变化处理
 * 当选择货位时，清空商品选择
 * @param selection 选中的货位列表
 */
const handleBinSelectionChange = (selection: BinItem[]) => {
  selectedBins.value = selection;

  // 清空商品选择
  selectedInboundProducts.value = [];
  totalInboundAmount.value = 0;
}

/**
 * 入库商品选择变化处理
 * 当选择商品时，计算总金额
 * @param selection 选中的商品列表
 */
const handleInboundProductSelectionChange = (selection: any[]) => {
  selectedInboundProducts.value = selection;
  calculateInboundTotal();
}

/**
 * 计算入库总金额
 * 根据选中的商品和数量计算总金额
 */
const calculateInboundTotal = () => {
  totalInboundAmount.value = selectedInboundProducts.value.reduce((sum, item) => {
    return sum + (item.unitPrice * item.inboundQuantity);
  }, 0);
}

/**
 * 获取库位表格行类名
 * 用于设置停用库位的样式
 * @param param0 行数据对象
 * @returns 行类名
 */
const getLocationRowClassName = ({ row }: { row: LocationItem }) => {
  if (row.status === 0) { // 停用状态
    return 'el-table__row--disabled';
  }
  return '';
}

/**
 * 获取货位表格行类名
 * 用于设置停用货位的样式
 * @param param0 行数据对象
 * @returns 行类名
 */
const getBinRowClassName = ({ row }: { row: BinItem }) => {
  if (row.status === 0) { // 停用状态
    return 'el-table__row--disabled';
  }
  return '';
}

/**
 * 获取入库表格行类名
 * 用于设置下架商品的样式
 * @param param0 行数据对象
 * @returns 行类名
 */
const getInboundRowClassName = ({ row }: { row: any }) => {
  if (row.status === 0) { // 下架状态
    return 'el-table__row--down';
  }
  return '';
}

/**
 * 获取货位类型标签类型
 * 根据货位类型返回对应的标签颜色类型
 * @param binType 货位类型
 * @returns 标签类型
 */
const getBinTypeTagType = (binType: string): string => {
  switch (binType) {
    case 'standard': return 'primary'   // 标准货位 - 蓝色
    case 'heavy': return 'warning'      // 重型货位 - 橙色
    case 'cold': return 'info'          // 冷藏货位 - 灰色
    case 'dangerous': return 'danger'   // 危险品货位 - 红色
    default: return 'info'
  }
}

/**
 * 获取货位类型标签文本
 * 根据货位类型返回对应的中文标签文本
 * @param binType 货位类型
 * @returns 货位类型文本
 */
const getBinTypeLabel = (binType: string): string => {
  switch (binType) {
    case 'standard': return '标准货位'
    case 'heavy': return '重型货位'
    case 'cold': return '冷藏货位'
    case 'dangerous': return '危险品货位'
    default: return '未知类型'
  }
}

/**
 * 提交入库操作
 * 将选中的商品入库到指定的货位
 */
const handleSubmitInbound = async () => {
  // 表单验证
  if (selectedInboundProducts.value.length === 0) {
    ElMessage.warning('请选择要入库的商品');
    return;
  }

  if (!inboundForm.warehouseId) {
    ElMessage.warning('请选择仓库');
    return;
  }

  if (selectedLocations.value.length === 0) {
    ElMessage.warning('请选择库位');
    return;
  }

  if (selectedBins.value.length === 0) {
    ElMessage.warning('请选择货位');
    return;
  }

  try {
    // 构造入库数据
    const inboundData = {
      orderId: selectedInboundOrder.value?.id,
      orderNo: selectedInboundOrder.value?.orderNo,
      warehouseId: inboundForm.warehouseId,
      locationIds: selectedLocations.value.map(location => location.id),
      binIds: selectedBins.value.map(bin => bin.id),
      inboundDate: new Date().toISOString(),
      inboundItems: selectedInboundProducts.value.map(item => ({
        productId: item.productId,
        productName: item.productName,
        specification: item.specification,
        unit: item.unit,
        inboundQuantity: item.inboundQuantity,
        unitPrice: item.unitPrice,
        subtotal: item.unitPrice * item.inboundQuantity
      })),
      totalAmount: totalInboundAmount.value,
      remark: inboundForm.remark || '',
      operator: 'admin'
    };

    console.log('提交入库数据:', inboundData);

    // 调用入库API
    const response = await http.post('/api/WMS_Inbound/CreateInbound', inboundData);

    if (response.data.code === 200) {
      ElMessage.success('入库操作成功！');
      inboundDialogVisible.value = false;
      loadData(); // 刷新采购订单列表
    } else {
      ElMessage.error(response.data.message || '入库操作失败');
    }
  } catch (error) {
    console.error('入库操作失败:', error);
    ElMessage.error('入库操作失败，请检查网络连接');
  }
}









// 事件处理
const handleSearch = () => { currentPage.value = 1; loadData() }
const handleReset = () => { Object.assign(searchForm, { OrderNo: '', SupplierId: '', dateRange: [] }); handleSearch() }
const handlePurchase = () => {
  purchaseDialogVisible.value = true;
  getSupplierList();
}
const handleExport = () => ElMessage.success('导出功能')
const handleSelectionChange = (selection: any) => { selectedRows.value = selection; hasSelection.value = selection.length > 0 }
const handleSizeChange = (size: any) => { pageSize.value = size; currentPage.value = 1; loadData() }
const handleCurrentChange = (page: any) => { currentPage.value = page; loadData() }

// 编辑和删除操作
const handleEdit = (row: any) => ElMessage.info(`编辑订单：${row.orderNo}`)
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除订单"${row.orderNo}"吗？`, '确认删除', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  }).then(() => { ElMessage.success('删除成功'); loadData() })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条数据吗？`, '确认删除', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  }).then(() => { ElMessage.success('批量删除成功'); loadData() })
}

// 获取表格行类名
const getRowClassName = ({ row }: { row: any }) => {
  if (row.status === 0) { // 假设0代表下架
    return 'el-table__row--down';
  }
  return '';
};

onMounted(loadData)
onMounted(getSupplierList)
</script>

<style scoped>
/* 基础容器样式 */
.demo-container {
  padding: 20px;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 25%, #0f3460 50%, #1a1a2e 75%, #16213e 100%);
  background-image:
    radial-gradient(circle at 20% 80%, rgba(66, 165, 245, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(92, 107, 192, 0.1) 0%, transparent 50%);
  min-height: 100vh;
  position: relative;
}

/* 纹理背景 */
.demo-container::before {
  content: '';
  position: absolute;
  inset: 0;
  background-image:
    linear-gradient(rgba(255, 255, 255, 0.02) 1px, transparent 1px),
    linear-gradient(90deg, rgba(255, 255, 255, 0.02) 1px, transparent 1px);
  background-size: 20px 20px;
  pointer-events: none;
  z-index: 0;
}

.demo-container>* {
  position: relative;
  z-index: 1;
}

/* 卡片通用样式 */
.card {
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.92) !important;
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);
}

/* 页头和操作区 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

/* 分页区域 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-card) {
  border-radius: 12px;
  transition: all 0.3s ease;
}

:deep(.el-card:hover) {
  transform: translateY(-2px);
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.3) !important;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid rgba(235, 238, 245, 0.5);
  background: rgba(248, 249, 250, 0.5);
  border-radius: 12px 12px 0 0;
}

:deep(.el-table) {
  margin-top: 10px;
  background: transparent;
}

:deep(.el-table__header-wrapper) {
  background: rgba(64, 158, 255, 0.1);
}

:deep(.el-table__body-wrapper) {
  background: transparent;
}

:deep(.el-breadcrumb__inner) {
  color: #2c3e50;
  font-weight: 500;
}

:deep(.el-breadcrumb__inner:hover) {
  color: #409EFF;
}

/* 订单详情弹窗样式 */
.order-details {
  padding: 10px 0;
}

.order-details h4 {
  margin: 20px 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

:deep(.el-descriptions__title) {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

/* 采购商品弹窗样式 */
.purchase-form {
  padding: 20px;
}

.purchase-form h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input-number) {
  width: 100px;
}

:deep(.el-table) {
  margin-top: 10px;
}

:deep(.el-table__header-wrapper) {
  background: rgba(64, 158, 255, 0.1);
}

:deep(.el-table__body-wrapper) {
  background: transparent;
}

:deep(.el-tag) {
  font-size: 14px;
}

/* 下架商品样式 */
:deep(.el-table__row--down) {
  background-color: #f5f7fa !important;
  color: #c0c4cc;
}

:deep(.el-table__row--down .el-checkbox) {
  pointer-events: none;
}

:deep(.el-table__row--down .el-input-number) {
  pointer-events: none;
  opacity: 0.6;
}
</style>
